package com.springcloud.eshop.datasync.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.springcloud.eshop.datasync.rabbitmq.factory.DataChangeHandlerFactory;
import com.springcloud.eshop.message.DataChangeMessage;
import com.springcloud.eshop.datasync.rabbitmq.strategy.BaseDataChangeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @Desc:
 * @Date: 2020-06-29
 * @Version:v1.0
 */
@Repository
@RabbitListener(queues = "data-change-queue")
public class RabbitmqConsumer {

    private Logger logger = LoggerFactory.getLogger(RabbitmqConsumer.class);

    @RabbitHandler
    public void handlerMessage(String messageStr, Channel channel, Message message) throws IOException {
        try {
            logger.info("RabbitmqConsumer.handlerMessage ,message : {}", messageStr);
            if (StringUtils.isEmpty(messageStr)) {
                return;
            }
            DataChangeMessage dataChangeMessage = JSON.parseObject(messageStr, DataChangeMessage.class);
            BaseDataChangeHandler dataChangeHandler = DataChangeHandlerFactory.getDataChangeHandler(dataChangeMessage.getDataType());
            dataChangeHandler.handler(dataChangeMessage);
            logger.info("RabbitmqConsumer.handlerMessage success,dataChangeMessage : {}", JSON.toJSONString(dataChangeMessage));
        } catch (Exception e) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }

    }
}
